package com.jgads.adapter;

import android.content.Context;

import com.anythink.core.api.ATAdConst;
import com.anythink.core.api.ATBiddingListener;
import com.anythink.core.api.ATBiddingResult;
import com.anythink.core.api.MediationInitCallback;
import com.anythink.nativead.unitgroup.api.CustomNativeAdapter;
import com.junion.ad.NativeExpressAd;
import com.junion.ad.bean.NativeExpressAdInfo;
import com.junion.ad.entity.JUnionAdSize;
import com.junion.ad.error.JUnionError;
import com.junion.ad.listener.NativeExpressAdListener;

import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: maipian
 * @CreateDate: 2021/12/7 2:57 PM
 */
public class NativeAdapter extends CustomNativeAdapter {

    private String slotId;
    private boolean isBidding;
    private int width;
    private NativeExpressAd nativeExpressAd;
    private ATBiddingListener biddingListener;
    private MExpressAd mNativeExpressAd;

    @Override
    public void loadCustomNetworkAd(final Context context, Map<String, Object> serverExtra, Map<String, Object> localExtra) {
        if (serverExtra.containsKey("slot_id")) {
            slotId = (String) serverExtra.get("slot_id");
        }

        width = 0;
        try {
            if (localExtra.containsKey(ATAdConst.KEY.AD_WIDTH)) {
                width = Integer.parseInt(localExtra.get(ATAdConst.KEY.AD_WIDTH).toString());
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }

        InitManager.getInstance().
                initSDK(context, serverExtra, new MediationInitCallback() {
                    @Override
                    public void onSuccess() {
                        startLoad(context);
                    }

                    @Override
                    public void onFail(String errorMsg) {
                        if (mLoadListener != null) {
                            mLoadListener.onAdLoadError("-1001", errorMsg);
                        }
                    }
                });

    }

    @Override
    public boolean startBiddingRequest(final Context context, Map<String, Object> serverExtra, Map<String, Object> localExtra, ATBiddingListener biddingListener) {
        this.isBidding = true;
        this.biddingListener = biddingListener;
        if (serverExtra.containsKey("slot_id")) {
            slotId = (String) serverExtra.get("slot_id");
        }

        width = 0;
        try {
            if (localExtra.containsKey(ATAdConst.KEY.AD_WIDTH)) {
                width = Integer.parseInt(localExtra.get(ATAdConst.KEY.AD_WIDTH).toString());
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }

        InitManager.getInstance().
                initSDK(context, serverExtra, new MediationInitCallback() {
                    @Override
                    public void onSuccess() {
                        startLoad(context);
                    }

                    @Override
                    public void onFail(String s) {
                        if (mLoadListener != null) {
                            mLoadListener.onAdLoadError("-1001", s);
                        }
                    }
                });
        return true;
    }

    private void startLoad(final Context context) {
        postOnMainThread(new Runnable() {
            @Override
            public void run() {
                if (width == 0) {
                    width = context.getResources().getDisplayMetrics().widthPixels;
                }
                nativeExpressAd = new NativeExpressAd(context, new JUnionAdSize(width, 0));
                nativeExpressAd.setListener(new NativeExpressAdListener() {
                    @Override
                    public void onRenderFailed(NativeExpressAdInfo nativeExpressAdInfo, JUnionError error) {
                        if (mLoadListener != null) {
                            mLoadListener.onAdLoadError("" + error.getCode(), "" + error.getError());
                        }
                    }

                    @Override
                    public void onAdReceive(List<NativeExpressAdInfo> adInfos) {
                        if (isBidding) {
                            if (biddingListener != null) {
                                if (adInfos == null || adInfos.size() == 0) {
                                    biddingListener.onC2SBiddingResultWithCache(
                                            ATBiddingResult.fail("adInfo no ad"),
                                            null);
                                } else {
                                    NativeExpressAdInfo nativeExpressAdInfo = adInfos.get(0);
                                    mNativeExpressAd = new MExpressAd(context, nativeExpressAdInfo, true);
                                    biddingListener.onC2SBiddingResultWithCache(
                                            ATBiddingResult.success(nativeExpressAdInfo.getBidPrice(), nativeExpressAdInfo.getKey(), null, ATAdConst.CURRENCY.RMB_CENT),
                                            mNativeExpressAd);
                                }
                            }
                        } else {
                            if (mLoadListener != null) {
                                if (adInfos == null || adInfos.size() == 0) {
                                    mLoadListener.onAdLoadError("-1002", "adInfo no ad");
                                } else {
                                    mNativeExpressAd = new MExpressAd(context, adInfos.get(0), false);
                                    mLoadListener.onAdCacheLoaded(mNativeExpressAd);
                                }
                            }
                        }
                    }

                    @Override
                    public void onAdExpose(NativeExpressAdInfo adInfo) {
                        if (mNativeExpressAd != null) {
                            mNativeExpressAd.onAdExpose(adInfo);
                        }
                    }

                    @Override
                    public void onAdClick(NativeExpressAdInfo adInfo) {
                        if (mNativeExpressAd != null) {
                            mNativeExpressAd.onAdClick(adInfo);
                        }
                    }

                    @Override
                    public void onAdClose(NativeExpressAdInfo adInfo) {
                        if (mNativeExpressAd != null) {
                            mNativeExpressAd.onAdClose(adInfo);
                        }
                    }

                    @Override
                    public void onAdFailed(JUnionError error) {
                        if (isBidding) {
                            if (biddingListener != null) {
                                biddingListener.onC2SBiddingResultWithCache(
                                        ATBiddingResult.fail(error.getError())
                                        , null
                                );
                            }
                        } else {
                            if (mLoadListener != null) {
                                mLoadListener.onAdLoadError(
                                        "" + error.getCode()
                                        , "" + error.getError()
                                );
                            }
                        }
                    }
                });
                nativeExpressAd.loadAd(getNetworkPlacementId());
            }
        });


    }

    @Override
    public String getNetworkPlacementId() {
        return slotId;
    }

    @Override
    public String getNetworkSDKVersion() {
        return InitManager.getInstance().getNetworkVersion();
    }

    @Override
    public String getNetworkName() {
        return InitManager.getInstance().getNetworkName();
    }

    @Override
    public void destory() {
        if (nativeExpressAd != null) {
            nativeExpressAd.release();
            nativeExpressAd = null;
        }
        if (mNativeExpressAd != null) {
            mNativeExpressAd.destroy();
            mNativeExpressAd = null;
        }

        biddingListener = null;
    }
}
